package com.ams.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ams.protocol.http.DefaultServlet;
import com.ams.protocol.http.HttpContext;
import com.ams.protocol.http.HttpRequest;
import com.ams.protocol.http.HttpResponse;

public class HttpHandler extends ProtocolHandler {
    final private Logger logger = LoggerFactory.getLogger(HttpHandler.class);

    private String docRoot;

    public HttpHandler(String docRoot) {
        this.docRoot = docRoot;
    }

    public void run() {
        try {
            HttpRequest request = new HttpRequest(conn.getInputStream());
            HttpResponse response = new HttpResponse(conn.getOutputStream());

            request.parse();

            DefaultServlet servlet = new DefaultServlet(
                    new HttpContext(docRoot));
            servlet.service(request, response);

            if (request.isKeepAlive()) {
                conn.close(true);
            } else {
                conn.close();
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
    }

    public ProtocolHandler handlerFactory() {
        return new HttpHandler(docRoot);
    }

}